package io.seata.account.service.impl;

import io.seata.account.entity.Account;
import io.seata.account.mapper.AccountMapper;
import io.seata.account.service.AccountService;
import io.seata.common.dto.AccountDTO;
import io.seata.common.enums.RspStatusEnum;
import io.seata.common.exception.DefaultException;
import io.seata.common.response.ObjectResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 * @author ZengRJ
 */
@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Resource
    private AccountMapper accountMapper;

    @Override
    @Transactional
    public ObjectResponse deduct(AccountDTO accountDTO) {
        log.info("开始扣款");
        ObjectResponse objectResponse = new ObjectResponse();
        try {
            Account account = new Account();
            account.setUserId(accountDTO.getUserId());
            account.setMoney(accountDTO.getMoney());
            accountMapper.deduct(account);
        } catch (Exception e) {
            throw new DefaultException("扣款失败，可能是余额不足！", e);
        }
        log.info("扣款成功");
        objectResponse.setStatus(RspStatusEnum.SUCCESS.getCode());
        objectResponse.setMessage(RspStatusEnum.SUCCESS.getMessage());
        return objectResponse;
    }
}
